<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryRef"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item
        label="来访人姓名"
        prop="visitorName"
        label-width="100px"
        style="width: 250px"
      >
        <el-input
          v-model="queryParams.visitorName"
          placeholder="请输入来访人姓名"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="手机号" prop="phone">
        <el-input
          v-model="queryParams.phone"
          placeholder="请输入手机号"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="来访时间" style="width: 308px">
        <el-date-picker
          v-model="daterangeVisitTime"
          value-format="YYYY-MM-DD"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="default"
          plain
          @click="resetQuery"
          >全部</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          @click="handleVisitorTypeChange(1)"
          v-hasPermi="['le:registration:query']"
          >探访来访</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          @click="handleVisitorTypeChange(0)"
          v-hasPermi="['le:registration:query']"
          >参观来访</el-button
        >
      </el-col>
      <el-col :span="1.5" style="flex-grow: 1; display: flex; justify-content: flex-end;">
        <el-button
          type="primary"
          @click="handleAdd"
          v-hasPermi="['le:visitor:add']"
          style="width: 70px;"
          >来访登记</el-button
        >
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['le:visitor:edit']"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['le:visitor:remove']"
          >删除</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['le:visitor:export']"
          >导出</el-button
        >
      </el-col> -->
      <!-- <right-toolbar
        v-model:showSearch="showSearch"
        @queryTable="getList"
      ></right-toolbar> -->
    </el-row>

    <el-table
      v-loading="loading"
      :data="visitorList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="主键ID" align="center" prop="id" />
      <el-table-column label="来访类型" align="center" prop="visitorType">
        <template #default="scope">
          <dict-tag :options="visitor_type" :value="scope.row.visitorType" />
        </template>
      </el-table-column>
      <el-table-column label="来访人姓名" align="center" prop="visitorName" />
      <el-table-column label="手机号" align="center" prop="phone" />
      <el-table-column label="老人姓名" align="center" prop="elderlyId">
        <template #default="scope">
          <span v-for="item in elderlyList" :key="item.id">
            <span v-if="item.id === scope.row.elderlyId">
              {{ item.name }}
            </span>
          </span>
        </template>
      </el-table-column>
      <el-table-column
        label="来访时间"
        align="center"
        prop="visitTime"
        width="180"
      >
        <template #default="scope">
          <span>{{
            parseTime(scope.row.visitTime, "{y}-{m}-{d} {h}:{i}:{s}")
          }}</span>
        </template>
      </el-table-column>
      <el-table-column label="创建人" align="center" prop="creator">
        <template #default="scope">
          <span v-for="item in userList" :key="item.id">
            <span v-if="item.userId === scope.row.creator">
              {{ item.nickName }}
            </span>
          </span>
        </template>
      </el-table-column>
      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        width="180"
      >
        <template #default="scope">
          <span>{{
            parseTime(scope.row.createTime, "{y}-{m}-{d} {h}:{i}:{s}")
          }}</span>
        </template>
      </el-table-column>
      <!-- <el-table-column label="状态" align="center" prop="status">
        <template #default="scope">
          <dict-tag :options="reservation_status" :value="scope.row.status"/>
        </template>
      </el-table-column> -->
      <!-- <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template #default="scope">
          <el-button
            link
            type="primary"
            icon="Edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['le:visitor:edit']"
            >修改</el-button
          >
          <el-button
            link
            type="primary"
            icon="Delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['le:visitor:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column> -->
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改来访登记对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="visitorRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="来访类型" prop="visitorType">
          <el-select v-model="form.visitorType" placeholder="请选择来访类型">
            <el-option
              v-for="dict in visitor_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="来访人姓名" prop="visitorName">
          <el-input v-model="form.visitorName" placeholder="请输入来访人姓名" />
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="form.phone" placeholder="请输入手机号" />
        </el-form-item>
        <!-- 修改老人外键编号输入框为带搜索的下拉框 -->
        <el-form-item label="老人选择" prop="elderlyId">
          <el-select
            v-model="form.elderlyId"
            placeholder="请选择或搜索老人"
            filterable
            clearable
            style="width: 100%"
          >
            <el-option
              v-for="elderly in elderlyList"
              :key="elderly.id"
              :label="`${elderly.name} (${elderly.idCard})`"
              :value="elderly.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="来访时间" prop="visitTime">
          <el-date-picker
            clearable
            v-model="form.visitTime"
            type="datetime"
            value-format="YYYY-MM-DD HH:mm:ss"
            placeholder="请选择来访时间"
          >
          </el-date-picker>
        </el-form-item>
        <!-- <el-form-item label="创建人" prop="creator">
          <el-input v-model="form.creator" placeholder="请输入创建人" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="form.status" placeholder="请选择状态">
            <el-option
              v-for="dict in reservation_status"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item> -->
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Visitor">
import {
  listVisitor,
  getVisitor,
  delVisitor,
  addVisitor,
  updateVisitor,
} from "@/api/le/visitor";
// ========== 新增：导入用户store以获取登录用户信息 ==========
import { useUserStore } from "@/store/modules/user";

const { proxy } = getCurrentInstance();
const { reservation_status, visitor_type } = proxy.useDict(
  "reservation_status",
  "visitor_type"
);

// ========== 新增：创建用户store实例 ==========
const userStore = useUserStore();

const visitorList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const daterangeVisitTime = ref([]);

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    visitorName: null,
    phone: null,
    visitTime: null,
    visitorType: null,
  },
  rules: {
    visitorType: [
      { required: true, message: "来访类型不能为空", trigger: "change" },
    ],
    visitorName: [
      { required: true, message: "来访人姓名不能为空", trigger: "blur" },
    ],
    phone: [{ required: true, message: "手机号不能为空", trigger: "blur" }],
    elderlyId: [{ required: true, message: "老人不能为空", trigger: "blur" }],
    visitTime: [
      { required: true, message: "来访时间不能为空", trigger: "blur" },
    ],
    creator: [{ required: true, message: "创建人不能为空", trigger: "blur" }],
    createTime: [
      { required: true, message: "创建时间不能为空", trigger: "blur" },
    ],
    status: [{ required: true, message: "状态不能为空", trigger: "change" }],
  },
});

const { queryParams, form, rules } = toRefs(data);

/** 查询来访登记列表 */
function getList() {
  loading.value = true;
  queryParams.value.params = {};
  if (null != daterangeVisitTime && "" != daterangeVisitTime) {
    queryParams.value.params["beginVisitTime"] = daterangeVisitTime.value[0];
    queryParams.value.params["endVisitTime"] = daterangeVisitTime.value[1];
  }
  listVisitor(queryParams.value).then((response) => {
    visitorList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// ========== 新增：解析并存储当前登录用户信息 ==========
const parseCurrentUserInfo = () => {
  try {
    // 检查用户store是否可用
    if (!userStore) {
      return null;
    }
    
    // 从用户store获取当前登录用户信息
    const currentUser = {
      id: userStore.id || null,
      nickName: userStore.nickName || "",
      name: userStore.name || "",
      roles: userStore.roles || [],
    };
    
    return currentUser;
  } catch (error) {
    console.error("解析用户信息失败:", error);
    return null;
  }
};

// 表单重置
function reset() {
  form.value = {
    id: null,
    visitorType: null,
    visitorName: null,
    phone: null,
    elderlyId: null,
    visitTime: null,
    creator: null,
    createTime: null,
    status: null,
    extraField1: null,
    extraField2: null,
  };
  proxy.resetForm("visitorRef");
}
function handleVisitorTypeChange(visitorType) {
  queryParams.value.visitorType = visitorType;
  handleQuery();
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  daterangeVisitTime.value = [];
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加来访登记";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value;
  getVisitor(_id).then((response) => {
    form.value = response.data;
    open.value = true;
    title.value = "修改来访登记";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["visitorRef"].validate((valid) => {
    if (valid) {
      if (form.value.id != null) {
        updateVisitor(form.value).then((response) => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        // ========== 新增：添加新来访登记时自动设置创建人和创建时间 ==========
        const currentUser = parseCurrentUserInfo();
        if (currentUser && currentUser.id) {
          form.value.creator = currentUser.id;
          // 修复时间格式：使用后端期望的格式 "yyyy-MM-dd HH:mm:ss"
          const now = new Date();
          const year = now.getFullYear();
          const month = String(now.getMonth() + 1).padStart(2, '0');
          const day = String(now.getDate()).padStart(2, '0');
          const hours = String(now.getHours()).padStart(2, '0');
          const minutes = String(now.getMinutes()).padStart(2, '0');
          const seconds = String(now.getSeconds()).padStart(2, '0');
          form.value.createTime = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
        } else {
          console.warn("无法获取当前用户信息，跳过设置创建人和创建时间");
        }
        
        addVisitor(form.value).then((response) => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal
    .confirm('是否确认删除来访登记编号为"' + _ids + '"的数据项？')
    .then(function () {
      return delVisitor(_ids);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download(
    "le/visitor/export",
    {
      ...queryParams.value,
    },
    `visitor_${new Date().getTime()}.xlsx`
  );
}

// 添加搜索过滤相关的响应式变量
const searchQuery = ref("");
const filteredElderlyList = ref([]);

// 监听搜索关键词变化，实时过滤老人列表
watch(searchQuery, (newVal) => {
  if (!newVal) {
    // 如果搜索词为空，显示所有老人
    filteredElderlyList.value = elderlyList.value;
  } else {
    // 否则根据姓名筛选（不区分大小写）
    const query = newVal.toLowerCase();
    filteredElderlyList.value = elderlyList.value.filter((elderly) =>
      elderly.name.toLowerCase().includes(query)
    );
  }
});

//获取老人列表
import { listElderly } from "@/api/le/elderly";
const elderlyList = ref([]);
const getElderlyList = () => {
  listElderly({
    pageNum: 1,
    pageSize: 1000,
  }).then((response) => {
    elderlyList.value = response.rows;
  });
};
//获取用户列表
import { listUser } from "@/api/system/user";
const userList = ref([]);
const getuserList = () => {
  listUser({
    pageNum: 1,
    pageSize: 1000,
  }).then((response) => {
    userList.value = response.rows;
  });
};

getList();
getElderlyList();
getuserList();
</script>
